# -*- coding: utf-8 -*-
#  列表转换成Excel文件的类
# @Time    ： 2023/3/2  23:23
# @Auther  ： 徐良
# File     :  outputXls.py
import pandas as pd
import openpyxl

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QFileDialog
from share.bioDialog import Infomation


def getFileName():
    filename, _ = QFileDialog.getSaveFileName(None, "Save Excel File", "", "Excel Files (*.xlsx)")

    if filename:
        # 如果用户选择了文件名和路径，将文件保存在该位置
        return filename
    else:
        # 如果用户没有选择文件名和路径，提示错误
        return ''


class ListsOutputXls(object):

    def __init__(self, win, data):
        super(ListsOutputXls, self).__init__()
        self._data = data
        self._win = win

    def do(self):
        toFile = pd.DataFrame(self._data)
        # 将数据导出到Excel文件

        # 弹出文件对话框，获取文件保存路径
        export_file_path, _ = QFileDialog.getSaveFileName(self._win, "保存到EXCEL文件", "", "Excel Files (*.xlsx)")

        # 如果用户选择了保存路径，则将数据导出到Excel文件中
        if export_file_path:
            toFile.to_excel(export_file_path, index=False, header=False)


class TreeWidgetToXls(object):

    def __init__(self, oList):
        """
        将多个treeWidget对象中的数据导出到一个Excel文件中
        :param oList: 元组列表，（标题名称，treeWidget对象)
        """
        super(TreeWidgetToXls, self).__init__()
        self.objList = oList

    def toXlsFile(self):
        fileName = getFileName()
        if fileName:
            workbook = openpyxl.Workbook()
            default_sheet = workbook['Sheet']
            workbook.remove(default_sheet)
        else:
            return

        for tup in self.objList:
            sheet_name = tup[0]
            treeW = tup[1]
            worksheet = workbook.create_sheet(sheet_name)

            header = treeW.headerItem()  # 获取树形控件的列表头
            count = header.columnCount()  # 获取列数
            row_data = [header.text(column) for column in range(count)]
            worksheet.append(row_data)

            # 将 QTreeWidgetItem 的数据写入 Excel 工作表
            for i in range(treeW.topLevelItemCount()):
                top_item = treeW.topLevelItem(i)
                row_data = [top_item.text(column) for column in range(top_item.columnCount())]
                worksheet.append(row_data)

                # 将子项的数据写入 Excel 工作表
                for j in range(top_item.childCount()):
                    child_item = top_item.child(j)
                    row_data = [child_item.text(column) for column in range(child_item.columnCount())]
                    worksheet.append(row_data)

        try:
            workbook.save(fileName)
        except Exception as e:
            print(e)
            Infomation.info('请关闭已打开的Excel文件.')


class TableWidgetToXls(object):
    def __init__(self, oList):
        """
        将多个tableWidget对象中的数据导出到一个Excel文件中
        :param oList: 元组列表，（标题名称，tableWidget对象)
        """
        super(TableWidgetToXls, self).__init__()
        self.objList = oList

    def toXlsFile(self):
        fileName = getFileName()
        if fileName:
            workbook = openpyxl.Workbook()
            default_sheet = workbook['Sheet']
            workbook.remove(default_sheet)
        else:
            return

        for tup in self.objList:
            sheet_name = tup[0]
            tableW = tup[1]
            worksheet = workbook.create_sheet(sheet_name)

            count = tableW.columnCount()  # 获取列数
            row_data = [tableW.horizontalHeaderItem(column).text() for column in range(count)]
            worksheet.append(row_data)


            # 获取 TableWidget 数据
            for row in range(tableW.rowCount()):
                for column in range(tableW.columnCount()):
                    item = tableW.item(row, column)
                    if item is not None:
                        worksheet.cell(row=row + 2, column=column + 1, value=str(item.text()))

        try:
            workbook.save(fileName)
        except Exception as e:
            print(e)
            Infomation.info('请关闭已打开的Excel文件.')


class TableViewToXls(object):

    def __init__(self, oList):
        super(TableViewToXls, self).__init__()
        self.objList = oList

    def toXlsFile(self):
        fileName = getFileName()
        if fileName:
            workbook = openpyxl.Workbook()
            default_sheet = workbook['Sheet']
            workbook.remove(default_sheet)
        else:
            return

        for tup in self.objList:
            sheet_name = tup[0]
            tableV = tup[1]
            worksheet = workbook.create_sheet(sheet_name)
            model = tableV.model()
            columns = model.columnCount()
            row_data = [model.headerData(column, Qt.Horizontal, Qt.DisplayRole) for column in range(columns)]
            worksheet.append(row_data)

            # 导每条记录
            rows = model.rowCount()
            for row in range(0, rows):
                row_data = []
                for column in range(columns):
                    index = model.index(row, column)
                    row_data.append(index.data())
                worksheet.append(row_data)
        try:
            workbook.save(fileName)
        except Exception as e:
            print(e)
            Infomation.info('请关闭已打开的Excel文件.')


class DfToXls(object):
    def __init__(self, DF):
        super(DfToXls, self).__init__()
        self.DF = DF

    def toXlsFile(self):
        fileName = getFileName()
        if fileName:
            try:
                self.DF.to_excel(fileName, '工艺文件', index=False)
            except IOError as e:
                Infomation.info('请关闭打开的文件')
            except Exception as e:
                pass
        else:
            return
